"use client";
import {
  List,
  ShowButton,
  DeleteButton,
  useTable,
} from "@refinedev/antd";
import { Space, Table, Button, Form, Input, Select, DatePicker, Card, Row, Col, Modal, message } from "antd";
import { useEffect, useState } from "react";
import { SearchOutlined, DeleteOutlined, ReloadOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import { cleanLogininfor } from "@common/api/logininfor_action";

const { RangePicker } = DatePicker;

export default function LogininforList() {
  const [datas, setDatas] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  const { tableProps, setCurrent, setPageSize, searchFormProps, tableQueryResult, setFilters } = useTable({
    resource: "system/logininfor/list",
    syncWithLocation: true,
    pagination: {
      current: 1,
    },
    onSearch: (values:any) => {
      return [
        {
          field: "user_name",
          operator: "eq",
          value: values.user_name,
        },
        {
          field: "ipaddr",
          operator: "eq",
          value: values.ipaddr,
        },
        {
          field: "status",
          operator: "eq",
          value: values.status,
        }
      ];
    },
  });
  console.log(searchFormProps);
  useEffect(() => {
    const res = tableProps?.dataSource as any;
    if (res && res.data) {
      const { list, total } = res.data;
      setDatas(list);
      setTotal(total);
    }
  }, [tableProps?.dataSource]);

  const handleReset = () => {
    setFilters([]);
    setCurrent(1);
  };

  const handleClean = () => {
    Modal.confirm({
      title: '确认清空',
      content: '确定要清空所有登录记录吗？此操作不可恢复！',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);
          const result: any = await cleanLogininfor();
          if (result.code === 200) {
            message.success('清空成功');
            tableQueryResult.refetch();
          } else {
            message.error(result.msg || '清空失败');
          }
        } catch (error) {
          message.error('操作失败');
        } finally {
          setLoading(false);
        }
      },
    });
  };

  const getStatusText = (status: string) => {
    return status === '0' ? '成功' : '失败';
  };

  const getStatusColor = (status: string) => {
    return status === '0' ? 'green' : 'red';
  };

  return (
    <List
      headerButtons={[
        <Button 
          key="refresh" 
          icon={<ReloadOutlined />}
          onClick={() => tableQueryResult.refetch()}
        >
          刷新
        </Button>,
        <Button 
          key="clean" 
          danger
          icon={<DeleteOutlined />}
          loading={loading}
          onClick={handleClean}
        >
          清空
        </Button>
      ]}
    >
      <Card style={{ marginBottom: 16 }}>
        <Form {...searchFormProps}>
          <Row gutter={16} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item name="user_name" label="用户名">
                <Input placeholder="请输入用户名" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="ipaddr" label="IP地址">
                <Input placeholder="请输入IP地址" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="请选择状态" allowClear>
                  <Select.Option value="0">成功</Select.Option>
                  <Select.Option value="1">失败</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="login_time" label="登录时间">
                <RangePicker 
                  showTime 
                  placeholder={['开始时间', '结束时间']}
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row style={{ marginTop: 16 }}>
            <Col>
              <Space>
                <Button type="primary" icon={<SearchOutlined />} onClick={searchFormProps.form?.submit}>
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      <Table 
        dataSource={datas} 
        rowKey="info_id" 
        loading={tableProps?.loading} 
        pagination={{
          showTotal: (total, range) => `总共 ${total} 条`,
          pageSize: 10,
          total: total,
          onChange: (page, pageSize) => {
            setCurrent(page);
            setPageSize(pageSize);
          },
        }}
      >
        <Table.Column dataIndex="info_id" title="访问ID" width={80} />
        <Table.Column dataIndex="user_name" title="用户名" width={120} />
        <Table.Column dataIndex="ipaddr" title="IP地址" width={120} />
        <Table.Column dataIndex="login_location" title="登录地点" width={150} />
        <Table.Column dataIndex="browser" title="浏览器" width={120} />
        <Table.Column dataIndex="os" title="操作系统" width={120} />
        <Table.Column 
          dataIndex="status" 
          title="状态" 
          width={80}
          render={(status) => (
            <span style={{ color: getStatusColor(status) }}>
              {getStatusText(status)}
            </span>
          )}
        />
        <Table.Column dataIndex="msg" title="提示消息" width={200} />
        <Table.Column 
          dataIndex="login_time" 
          title="登录时间" 
          width={180}
          render={(time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'}
        />
        <Table.Column
          title="操作"
          dataIndex="actions"
          width={120}
          fixed="right"
          render={(_, record) => (
            <Space>
              <ShowButton 
                hideText 
                size="small" 
                recordItemId={record.info_id}
                title="查看详情"
              />
              <DeleteButton 
                hideText 
                size="small" 
                recordItemId={record.info_id}
                title="删除"
              />
            </Space>
          )}
        />
      </Table>
    </List>
  );
} 